package com.ym.utils.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @ProjectName: SpringCloud-Alibaba-YM
 * @ClassName: RedisLock
 * @Description: TODO Redis 实现分布式锁
 * @Author: 晨曦
 * @Date: 2021-1-15 9:34
 */
public class RedisLock {
    private final static Logger log = LoggerFactory.getLogger(RedisLock.class);

    /**
     * 释放锁lua脚本
     */
    private static final String RELEASE_LOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private Boolean getRedisLock(String lockKey, String uuid) {
        boolean success = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 3, TimeUnit.MINUTES);
        if (!success) {
            log.info("锁已存在");
            return false;
        }
        return true;
    }

    private Boolean removeRedisLock(String lockKey, String uuid) {
        // 指定 lua 脚本，并且指定返回值类型
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT,Long.class);
        //  参数一：redisScript，参数二：key列表，参数三：arg（可多个）
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),uuid);
        if (result!=1) {
            log.info("解锁失败");
            return false;
        }
        return true;
    }

    /*public void contextLoads() {
        String lockKey = "123";
        //String uid = IdUtils.simpleUUID();
        String uid ="0101203";
        boolean success = redisTemplate.opsForValue().setIfAbsent(lockKey,uid,3, TimeUnit.MINUTES);
        if (!success){
            System.out.println("锁已存在");
        }
        // 指定 lua 脚本，并且指定返回值类型
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT,Long.class);
        //  参数一：redisScript，参数二：key列表，参数三：arg（可多个）
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),uid);
        System.out.println(result);
    }*/
}
